// One channel of ecg wave, use CustomPainterComponent/CustomPainter
// to draw wave, with WaveContext contains all info.
import 'package:flame/components.dart';
import 'package:flutter/material.dart';

import 'package:pmviewer/ecgpacket/ecgpacket.pbenum.dart';
import 'wavecontext.dart';

// customer painter widget, used by Flame's CustomPainterComponent to draw wave
class WavePainter extends CustomPainter {
  WaveContext drawWaveContext;
  WavePainter(this.drawWaveContext);

  @override
  void paint(Canvas canvas, Size size) {
    drawWaveContext.drawOutLine(canvas);
    drawWaveContext.drawWave(canvas);
    drawWaveContext.drawRuler(canvas);
    drawWaveContext.drawName(canvas);
    drawWaveContext.drawSpeed(canvas);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

// flutter flame component, to draw one channel of ecg wave
class EcgWave extends CustomPainterComponent {
  WaveContext waveContext;
  EcgChan ecgChan;
  EcgWave(
    this.waveContext,
    this.ecgChan, {
    super.position,
    int? priority,
  }) : super(
          priority: priority ?? double.maxFinite.toInt(),
          size: Vector2(300, 50),
        ) {
    painter = WavePainter(waveContext);
  }

  // flame rendered per frame
  @override
  void update(double dt) {
    super.update(dt);
    waveContext.UpdateData(dt);
  }

  void setPositionAndSize(Vector2 pos, Vector2 size) {
    position = pos;
    this.size = size;
    if (size.x < 0) size.x = 0;
    if (size.y < 0) size.y = 0;
    waveContext.setArea(Rect.fromLTWH(0, 0, size.x, size.y));
  }
}
